import groovy.xml.MarkupBuilder

/**
 *
 */

/**
 * <DL><DT>标题</DT></DL>
 *
 * @author liuboen
 *
 * @since 2012-9-17
 * @version 1.0.0
 */
class XmlTest {
	def  xmlstr = "<langs type=\"current\"><language>Java</language><language>Groovy</language><language>JavaScript</language></langs>";

	def static xmlParserTest(){
		def out2 =new StringWriter()
		def xml2 = new groovy.xml.MarkupBuilder(out2)
		xml2.langs(type:"current"){
		  language("Java")
		  language("Groovy")
		  language("JavaScript")
		}
		//XmlParser使用Gpath，返回Node，NodeList，以及属性对应的Map
		//所以你在访问xml文件中的属性时，也就如同访问list和map中的属性
		def langs = new XmlParser().parseText(out2.toString())
		//获取属性
		println "type = ${langs.attribute("type")}"
		//获取节点
		langs.language.each{
		  println it.text()
		}
		//结合使用Gpath和spread-dot
		def values = langs.language[1].text()
		
	}
	
	def static xmlSlurperTest(){
		def out =new StringWriter()
		MarkupBuilder xml = new MarkupBuilder(out)
		//构造一段xml如同构造一个java对象
		//groovy引擎在找不到name方法，address方法时，自动识别为添加元素
		xml.person{
			name(type:'berdy')
			address('上海')
			friends{
				for(i in 1..10)
					friend i
			}
		}
		//使用XmlSlurper，返回的是groovy.util.slurpersupport.GPathResult
		//使用XmlSluper访问xml时在写法上更加的便捷
		def slurperLangs = new XmlSlurper().parseText(out.toString())
		println "type = ${slurperLangs.name.@type}"
		
		slurperLangs.friends.friend.each{
		  println it
		}
		
	}
	
	static main(args) {
		xmlParserTest();
		//xmlSlurperTest()
	}

}
